A dropdownlist list in ASP.NET MVC although not [required] field shows up as required and Model Sta

Posted by VJ on Stack Overflow See other posts from Stack Overflow or by VJ
Published on 2010-05-12T20:26:50Z Indexed on 2010/05/12 20:44 UTC
Read the original article Hit count: 301

I have the following code-

View-

<% Html.BeginForm(); %>
     <div>
    <%= Html.DropDownList("DropDownSelectList", new SelectList( Model.DropDownSelectList, "Value", "Text"))%>

Controller-

public ActionResult Admin(string apiKey, string userId)
        {
 ChallengesAdminViewModel vm = new ChallengesAdminViewModel();
            vm.ApiKey = apiKey;
            vm.UserId = userId;
  vm.DropDownSelectList = new List<SelectListItem>();
            vm.DropDownSelectList.Add(listItem1);
            vm.DropDownSelectList.Add(listItem2);
            vm.DropDownSelectList.Add(listItem3);
            vm.DropDownSelectList.Add(listItem4);
            vm.DropDownSelectList.Add(listItem5);
            vm.DropDownSelectList.Add(listItem6);
            vm.DropDownSelectList.Add(listItem7);
}
 [HttpPost]
        public ActionResult Admin(ChallengesAdminViewModel vm)
        {
          if (ModelState.IsValid)//Due to the null dropdownlist  gives model state invalid
            {
}
}

ViewModel-

public class ChallengesAdminViewModel
    {
        [Required]
        public string ApiKey { get; set; }
         [Required]
        public string UserId { get; set; }
        public List<SelectListItem> DropDownSelectList { get; set; }

    }

I dont know why it still requires the list although not required. I want to have only two attributes as required. So I wanted to know how do i declare or change that list to be not required and have my Model State Valid.

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about fields